package helmdriver

import (
	"context"
	corev1 "gluenet/internal/agent/api/core/v1"
	"gluenet/internal/agent/depend"
	"gluenet/internal/agent/driver"
	"gluenet/internal/agent/driver/helmdriver/search"

	"github.com/spf13/viper"
	"helm.sh/helm/v3/pkg/release"
)

type HelmDriver interface {
	Install(namespace string, release corev1.Release) (*release.Release, error)

	Uninstall(namespace string, release corev1.Release) error

	Update(namespace string, release corev1.Release) error

	ListCharts(name string) ([]*search.Result, error)

	GetRelease(namespace, releaseName string) (*release.Release, error)

	ListRelease(namespace string) ([]*release.Release, error)

	ListAllRelease(namespaces []string) ([]*release.Release, error)
}

func init() {
	depend.Provide(NewHelmConfig)
	depend.Provide(NewHelmDriver)
}

const (
	keyHelmConfig = driver.KeyDriverPerfix + `helm`
)

type HelmConfig struct {
	KubePath string `mapstructure:"kube_path"`
	RepoName string `mapstructure:"repo_name"`
	RepoUrl  string `mapstructure:"repo_path"`
}

func NewHelmConfig(vp *viper.Viper) (*HelmConfig, error) {
	cfg := new(HelmConfig)
	if err := vp.UnmarshalKey(keyHelmConfig, cfg); err != nil {
		return nil, err
	}
	return cfg, nil
}

func NewHelmDriver(cfg *HelmConfig) (HelmDriver, error) {
	return NewDriver(
		context.Background(),
		cfg.RepoName,
		cfg.RepoUrl,
		cfg.KubePath,
	)
}
